package vertx;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;

public class UrlParamsVerticle extends AbstractVerticle {
  //第一步 声明路由
  Router router;

  @Override
  public void start(Promise<Void> startPromise) throws Exception {
    //第二部 初始化router
    router =Router.router(vertx);
    //第三步 将Router与vertx HttpServer 绑定

    //经典模式
    //localhost:8888/test?page=1&age=10
    router.route("/test").handler(
      req -> {
        //vert.x获取page参数
        String page = req.request().getParam("page");//vert.x获取Url参数
        req.response()
          //text/plain修改json格式application/json
          .putHeader("content-type", "application/json")
          .end(page);
      });
    //rest 模式
    router.route("/test/:page").handler(
      req -> {
        JsonObject bodyAsJson = req.getBodyAsJson();
        //vert.x获取page参数
        String page = req.request().getParam("page");//vert.x获取Url参数
        req.response()
          //text/plain修改json格式application/json
          .putHeader("content-type", "application/json")
          .end(page);
      });


    vertx.createHttpServer().requestHandler(router).listen(8888,http->{
      if (http.succeeded()) {
        startPromise.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startPromise.fail(http.cause());
      }
    });
  }
}
